package one.stand.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import one.stand.entity.ImageVEntity;
import one.stand.mapper.GlobalFileMapper;
import one.stand.model.GlobalFileModel;
import one.stand.model.ResultModel;
import one.stand.service.OssService;
import one.stand.util.FileMd5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class OssServiceImpl extends BaseService implements OssService {
    /**
     * 图片默认缩放比率
     */
    private  final double DEFAULT_SCALE = 0.5d;
    /**
     * 原图后缀
     */
    private final String primary=".primary.png";

    @Autowired
    FileMd5Util fileMd5Util;
    @Autowired
    GlobalFileMapper globalFileMapper;
    @Override
    public ResultModel<String> upload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return ResultModel.fail("文件为空");
        }
        Long size=file.getSize();
        if (size > fileSize) {
            logger.info("文件过大:"+size);
            return ResultModel.fail("文件过大");
        }
        String fileMd5=fileMd5Util.getFileMd5Value(file);
        GlobalFileModel globalFileModel=globalFileMapper.selectByPrimaryKey(fileMd5);
        if(null!=globalFileModel){
            log.info("重复文件：{}",globalFileModel);
            return ResultModel.success(globalFileModel.getFileUrl());
        }
        String url;
        ImageVEntity isImage=ossUtil.getType(file,fileMd5);
        if(isImage.isImage()){
            log.info("检测到是图片。。。。");
            //进行原图压缩
            log.info("进行压缩图片。。。。");
//            BufferedImage bufferedImage=Thumbnails.of(file.getInputStream()).size(375,375).asBufferedImage();
//            log.info("开始上传压缩版图片");
//            url = ossUtil.upload(bufferedImage,isImage);

            url=ossUtil.uploadObjectOSS(file,isImage);
            log.info("文件上传地址为：{}",url);
            log.info("开始上传原图");
            isImage.setUrl(isImage.getUrl()+primary);
            ossUtil.uploadObjectOSS(file,isImage);
        }else{
            log.info("检测到不是图片。。。。。。。。。。。。。");
            url=ossUtil.uploadObjectOSS(file,isImage);
        }

        globalFileModel=new GlobalFileModel();
        globalFileModel.setFileMd5(fileMd5);
        globalFileModel.setFileUrl(url);
        globalFileMapper.insertSelective(globalFileModel);
        return ResultModel.success(url);
    }




}
